#!/bin/bash

import os
import subprocess
import glob

# Loop through folders 1-28
for i in range(1, 29):
    folder = str(i)
    if os.path.isdir(folder):
        print(f"Processing folder {i}")
        
        # Change to the folder
        os.chdir(folder)
        
        # Find all .nii files that don't contain '_p_'
        nii_files = glob.glob("*.nii")
        regular_files = [f for f in nii_files if '_p_' not in f]
        
        for file1 in regular_files:
            # Generate the corresponding *p* file name (this will be created)
            file2 = file1.replace('_aligned_tf', '_p_aligned_tf')
            
            # Check if output file already exists (skip if it does)
            if os.path.isfile(file2):
                print(f"  Skipping {file1} - {file2} already exists")
            else:
                print(f"  Running: ../paste {file1} {file2}")
                try:
                    # Run the paste command
                    subprocess.run(['../paste', file1, file2], check=True)
                except subprocess.CalledProcessError as e:
                    print(f"  Error running paste command: {e}")
                except FileNotFoundError:
                    print("  Error: paste executable not found")
        
        # Go back to parent directory
        os.chdir('..')